// src/api/service/AuthService.tsx
import {STORAGE_KEY} from '../../config/Constant';

const apiUrl = import.meta.env.VITE_API_BASE_URL;
// 定义登录请求参数类型
export interface LoginRequest {
    username: string;
    password: string;
}

export interface LoginResponse {
    id?: string;
    username?: string;
    nickname?: string;
    avatar_addr?: string;
    status?: string;
    roles?: Roles[];
    authorities?: Authorities[];
    accounts?: Accounts[];
    access_token?: string;
    refresh_token?: string;
    create_time?: string;
    update_time?: string;
}

export interface Roles {
    id?: string;
    name?: string;
    user_id?: string;
    role_id?: string;
    create_time?: string;
    update_time?: string;
}

export interface Authorities {
    id?: string;
    name?: string;
    user_id?: string;
    authority_id?: string;
    create_time?: string;
    update_time?: string;
}

export interface Accounts {
    id?: string;
    user_id?: string;
    type?: string;
    account?: string;
    access_code?: string;
    create_time?: string;
    update_time?: string;
}

export interface Tokens {
    access_token?: string;
    refresh_token?: string;
}


class AuthService {
    /**
     * 用户登录
     * @param credentials 登录凭证
     * @returns 登录响应
     */
    async login(credentials: LoginRequest): Promise<LoginResponse> {
        try {

            // 发送 POST 请求到 /api/auth/login
            const response = await fetch(apiUrl + '/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(credentials),
                credentials: 'include'
            });

            // 检查响应状态
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            // 解析响应数据
            return await response.json();
        } catch (error) {
            console.error('登录请求失败:', error);
            // 返回一个空的 LoginResponse 对象而不是包含 success 和 message 的对象
            return {} as LoginResponse;
        }
    }


    /**
     * 用户登出
     */
    async logout(): Promise<void> {
        const response = await fetch(apiUrl + '/api/auth/logout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include'
        });

        // 检查响应状态
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        localStorage.removeItem(STORAGE_KEY.USER_INFO);
    }

    async refreshToken(): Promise<Tokens> {
        const response = await fetch(apiUrl + '/api/auth/refresh_token', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include'
        });

        // 检查响应状态
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return await response.json();
    }

}

// 创建并导出 AuthService 实例
export const authService = new AuthService();
